// dtdcxrt.C -- Extract the drift times, and integrate to obtain the rt relations
// for X wires of dcs after the dipole manget
// Created: Jul 9, 2024 by SUN Yazhou

void a(vector<TH1 *> &v, TH1 *h){ v.push_back((TH1 *)h); }
void dtdcxrt(){
  TFile *f = new TFile(getenv("TMP1"));
  TTree *etf = (TTree *)f->Get("etf");
  vector<TH1 *> v, vrt;
  TH1 *h0, *h1;
  char zcut[64] = "";
  static const int Z = 29;
  if(Z > 0) sprintf(zcut, "az0>%.2f && az0<%.2f", Z-0.5, Z+0.5);

  const char xuv[3] = {'X', 'U', 'V'};
  char hname[64]{}, layer[64]{};
  for(int i = 0; i < 3; i++){ // loop over dc0-1-2
    for(int j = 0; j < 1; j++){ // limited to X only
      sprintf(layer, "dc%d%c", i, xuv[j]);
      sprintf(hname, "hdc%d", i);
      h0 = new TH1F(hname, Form("Drift Time for %s", layer), 2000, -100., 400.);
      h0->GetXaxis()->SetTitle("drift time [ns]");
      h0->GetYaxis()->SetTitle("counts");
      h1 = new TH1F(Form("hrt_dc%d", i), Form("R(t) for %s", layer), 2000, -100., 400.);
      h1->SetLineColor(2);
      h1->GetXaxis()->SetTitle("drift time [ns]");
      h1->GetYaxis()->SetTitle("drift distance [mm]");
      a(v, h0); a(vrt, h1);
      for(int k = 0; k < 2; k++)
        etf->Project(Form("+%s", hname), Form("%s%d.GetT()", layer, k),
          Form("%s&&fabs(postMagTrackerX.ang()-15.)<1.&&%s%d.fired()>=2", zcut, layer, k));
      for(int i = 1; i < h0->GetNbinsX(); i++) h1->SetBinContent(i, h0->Integral(1, i));
      h1->Scale(5./h0->Integral());
      cout << "Processing " << layer << ": " << zcut << "...\r" << flush;
    } // end for over dc0-1-2
  } // end for over U, D
  cout << endl;

  TCanvas *c = new TCanvas("c", "Integrate t for R(t) for dcTa-s", 1680, 1050);
  c->Divide(2, 3);
  int id = 0;
  // c->Print("dtdcxrt.pdf[");
  for(int i = 0; i < 3; i++){ // loop over dc0-1-2
    c->cd(2*i+1); v[id]->Draw();
    c->cd(2*i+2); vrt[id++]->Draw();
  // c->Print("dtdcxrt.pdf");
  } // end for over i
  c->Print("dtdcxrt.pdf");
  // c->Print("dtdcxrt.pdf]");

  TFile *frt = new TFile("rt.root", "UPDATE");
  for(auto h : vrt) h->Write("", TObject::kOverwrite);
} // end dtdcxrt
